<template>
<!--pages/tools/wangdian/select/select.wxml-->
<view class="body">
	<view class="header flex">
		<image src="http://imgbdb3.bendibao.com/whbdb/202011/11/20201111092541_78494.png" class="local-icon"></image>
		<view class="city" @tap="toggleAddress">{{ local }}</view>
		<image src="http://imgbdb3.bendibao.com/whbdb/202011/11/20201111092824_71951.png" class="arrow-down"></image>
	</view>
	<view class="city-select" v-if="showAddress && province">
		<view class="address flex">
			<scroll-view :scroll-y="true" class="province flex col">
				<view v-for="(item, index) in province" :key="index" :class="'name ' + (item.chouse? 'chouse':'')" @tap="addressClick" :data-index="index" data-type="province">
					{{ item.cityname }}
				</view>
			</scroll-view>
			<scroll-view :scroll-y="true" class="city flex col">
				<view v-for="(item, index) in city" :key="index" :class="'name ' + (item.chouse? 'chouse':'')" @tap="addressClick" :data-index="index" data-type="city">
					{{ item.cityname }}
				</view>
			</scroll-view>
			<scroll-view :scroll-y="true" class="qu flex col">
				<view v-for="(item, index) in district" :key="index" :class="'name ' + (item.chouse? 'chouse':'')" @tap="addressClick" :data-index="index" data-type="district">
					{{ item.cityname }}
				</view>
			</scroll-view>
		</view>
		<view class="black" @tap="toggleAddress" catchtouchmove="ture"></view>
	</view>
	<view class="search flex">
		<image src="/static/images/index/sousuo.png" class="search-icon"></image>
		<input class="input" @input="keywords" :placeholder="'请输入' + type[typeIndex] + '名称，例如' + (type[typeIndex] == '网点' ? '派出所' : '入户')" :value="keywords" @confirm="search">
		<view class="type flex">
			<picker mode="selector" @change="typeChange" :range="type">{{ type[typeIndex] }}</picker>
			<image src="/static/images/dwicon.png" class="select-icon"></image>
		</view>
	</view>
	<!--  最近搜索 -->
	<view class="lately-search flex" v-if="shwoHistory">
		<view class="lately-title">最近搜索：</view>
		<view v-for="(item, index) in history" :key="index" class="lately-item" @tap="setKeywords" :data-name="item.name" :data-type="item.type">{{ item.name }}</view>
	</view>

	<!--  热门搜索 -->
	<view class="lately-search flex" v-if="hotSearch">
		<view class="lately-title">热门搜索：</view>
		<view v-for="(item, index) in hotSearch" :key="index" class="lately-item" @tap="setKeywords" :data-name="item.ci" :data-type="typeIndex+1">{{ item.ci }}</view>
	</view>
	<view class="info-list" v-if="webInfo">
		<view v-for="(item, index) in webInfo" :key="index" class="info-item" @tap="toDetail" :data-index="index">
			<view class="info-title">{{ item.com_name }}</view>
			<view class="border flex row-between">
				<view class="info flex col">
					<view class="base flex">
						<view class="distance" v-if="item.distance">{{ item.distance }}</view>
						<view class="addr text-over" v-if="item.com_addr">{{ item.com_addr }}</view>
					</view>
					<view class="local" v-if="item.classname">
						<image src="http://imgbdb3.bendibao.com/whbdb/202012/3/20201203113324_24608.png" mode></image>
						<text>{{ item.classname }}</text>
					</view>
					<view class="time" v-if="item.com_yytime">
						<image src="http://imgbdb3.bendibao.com/whbdb/202012/3/20201203112840_58950.jpg" mode></image>
						<text>{{ item.com_yytime }}</text>
					</view>
				</view>
				<view class="control flex">
					<image src="http://imgbdb3.bendibao.com/whbdb/202012/2/20201202181224_15478.png" @tap.stop="shwoDetail" :data-index="index"></image>
					<image src="http://imgbdb3.bendibao.com/whbdb/202012/2/20201202181246_36743.png" @tap.stop="navigator" :data-name="item.com_name" :data-addr="item.com_addr" :data-index="index" :data-lat="item.com_wd" :data-lng="item.com_jd"></image>
				</view>
			</view>
		</view>
	</view>
	<view class="no-info" v-else></view>

</view>
</template>

<script>
// pages/tools/wangdian/select/select.js
//获取应用实例
var app = getApp();
const util = require("../../../../utils/util.js");
var QQMapWX = require("../../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js");
var qqmapsdk = new QQMapWX({
  key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});
let defaultCity;

export default {
  data() {
    return {
      type: ['网点', '业务'],
      typeIndex: 0,
      keywords: '',
      history: [],
      webInfo: [],
      shwoHistory: true,
      range: '',
      showPop: false,
      opentype: '',
      data: {},
      hotSearch: "",
      cityCode: 'sz',
      lat: '',
      lng: '',
      isLast: false,
      //是否最后一页
      count: 0,
      //总条数
      page: 1,
      //第几页
      provinceName: '广州市',
      cityName: '深圳市',
      districtName: '南山区',
      local: '深圳市',
      //显示地点
      province: [],
      provinceIndex: 0,
      city: [],
      cityIndex: 0,
      district: [],
      districtIndex: 0,
      showAddress: false,
      getCity: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.getUrl(app.globalData.url).then(e => {
      util.request('network.php', {
        action: 'get_citys'
      }, 'POST').then(res => {
        if (res.data.state == 1) {
          res.data.data.forEach(item => item.chouse = false);
          res.data.data.unshift({
            cityname: '默认',
            citycode: 'mr',
            id: 0,
            chouse: true
          });
          this.setData({
            province: res.data.data
          });
          util.request('network.php', {
            action: 'get_cityid',
            cityname: options.cityName || this.cityName
          }, 'POST').then(res => {
            this.setData({
              city: res.data.data
            });
            defaultCity = JSON.parse(JSON.stringify(this.city));
            qqmapsdk.reverseGeocoder({
              success: () => {},
              fail: () => {},
              complete: res => {
                const lat = res.result ? res.result.location.lat : '';
                const lng = res.result ? res.result.location.lng : '';
                this.history = uni.getStorageSync('history') ? JSON.parse(uni.getStorageSync('history')) : '';
                this.keywords = options.keywords;
                this.setData({
                  history: this.history,
                  keywords: this.keywords,
                  typeIndex: options.type ? parseInt(options.type) - 1 : 0,
                  lat,
                  lng,
                  provinceName: options.provinceName || this.provinceName,
                  cityName: options.cityName || this.cityName,
                  districtName: options.districtName || this.districtName,
                  cityCode: options.cityCode,
                  local: options.districtName == '全部' ? options.cityName : options.cityName + options.districtName
                });

                if (this.keywords) {
                  this.getInfo();
                }

                ;
                this.getHotSearch();
                this.getDistrict(this.districtName);
              }
            });
          });
        }
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.isLast) {
      this.setData({
        page: this.page + 1
      });
      this.getInfo();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: `本地宝-网点查询-${this.keywords}-查询`,
      imageUrl: "http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg",
      path: `/pages/tools/wangdian/select/select?keywords=${this.keywords}&type=${this.typeIndex + 1}&provinceName=${this.provinceName}&cityName=${this.cityName}&districtName=${this.districtName}&cityCode=${this.cityCode}`
    };
  },
  methods: {
    // 开关选择城市
    toggleAddress() {
      this.setData({
        showAddress: !this.showAddress
      });
    },

    // 选择城市
    addressClick(e) {
      let index = util.getValue('index', e);
      let type = util.getValue('type', e);
      this[`${type}Index`] = index;
      this[type].forEach(item => item.chouse = false);
      let data = this[type][index];
      data.chouse = true;
      this.setData({//[`${type}Index`]: this.data[`${type}Index`]
        //[type]: this.data[type]
      });
      //try fix
      this[type] = this[type];
      //try fix
      this[`${type}Index`] = this[`${type}Index`];

      switch (type) {
        case 'province':
          {
            this.setData({
              district: []
            });

            if (data.cityname == '默认') {
              this.setData({
                city: defaultCity
              });
            } else {
              this.getCity();
            }
          }
          break;

        case 'city':
          this.getDistrict();
          break;

        case 'district':
          {
            this.showAddress = false;
            let district = this.district[this.districtIndex].id ? this.district[this.districtIndex].cityname : '全部';
            this.local = `${this.city[this.cityIndex].cityname}${this.district[this.districtIndex].cityname}`;
            this.setData({
              showAddress: this.showAddress,
              local: this.local,
              provinceName: this.province[this.provinceIndex].cityname,
              cityName: this.city[this.cityIndex].cityname,
              districtName: district,
              cityCode: this.city[this.cityIndex].citycode
            });
            this.search();
          }
          break;

        default:
          {}
      }
    },

    // 获得城市
    getCity() {
      if (!this.province[this.provinceIndex].city) util.request('network.php', {
        action: 'get_citys',
        proviceid: this.province[this.provinceIndex].id
      }, 'POST').then(res => {
        if (res.data.state == 1) {
          res.data.data.forEach(item => item.chouse = false);
          this.city = res.data.data;
          this.province[this.provinceIndex].city = res.data.data;
          this.setData({
            city: this.city,
            getCity: this.province
          });
        }
      });else {
        this.city = this.province[this.provinceIndex].city;
        this.setData({
          city: this.city
        });
      }
    },

    // 获得区
    getDistrict(district) {
      if (this.city[this.cityIndex].district) {
        this.district = this.city[this.cityIndex].district;
        this.districtIndex = this.district.findIndex(item => item.cityname == district);
        this.setData({
          district: this.city[this.cityIndex].district,
          districtIndex: this.districtIndex
        });
      } else {
        util.request('network.php', {
          action: 'get_citys',
          cityid: this.city[this.cityIndex].id
        }, 'POST').then(res => {
          if (res.data.state == 1) {
            res.data.data.forEach(item => item.chouse = false);
            res.data.data.unshift({
              id: '',
              citycode: '',
              cityname: '全市'
            });
            this.district = res.data.data;
            this.city[this.cityIndex].district = this.district;
            this.districtIndex = this.district.findIndex(item => item.cityname == district);
            this.setData({
              district: this.district,
              city: this.city,
              districtIndex: this.districtIndex
            });
          }
        });
      }
    },

    //双向绑定keywords
    keywords(e) {
      this.setData({
        keywords: e.detail.value
      });
    },

    // 类型切换
    typeChange(e) {
      this.setData({
        typeIndex: parseInt(e.detail.value)
      });
      this.getHotSearch();
    },

    // 关键字搜索
    setKeywords(e) {
      let name = util.getValue('name', e);
      let type = util.getValue('type', e);
      this.setData({
        keywords: name,
        typeIndex: parseInt(type) - 1
      });
      this.setData({
        page: 1,
        webInfo: []
      });
      this.getInfo();
    },

    // 搜索
    search() {
      if (this.keywords.trim()) {
        util.addHistory({
          name: this.keywords,
          type: parseInt(this.typeIndex) + 1
        });
      }

      this.setData({
        page: 1,
        webInfo: []
      });
      this.getInfo();
    },

    //获取热门评论
    getHotSearch() {
      util.request("network.php", {
        citycode: this.cityCode,
        type: this.type[this.typeIndex],
        action: "hot"
      }, "POST").then(res => {
        if (res.data) {
          this.setData({
            hotSearch: res.data
          });
        }
      });
    },

    //获取列表
    getInfo() {
      let data = {
        keywords: this.keywords,
        lat: this.lat,
        lnt: this.lng,
        type: parseInt(this.typeIndex) + 1,
        provice: this.provinceName,
        city: this.cityName,
        county: this.districtName,
        page: this.page,
        action: 'search'
      };
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      util.request('network.php', data, 'POST').then(res => {
        if (res.data.data.search.length) {
          res.data.data.search.forEach(item => {
            this.setData({
              shwoHistory: false
            });

            if (item.distance) {
              item.distance = item.distance < 1 ? `${(parseFloat(item.distance) * 1000).toFixed(0)}米` : `${parseFloat(item.distance).toFixed(2)}公里`;
            }
          });
          this.setData({
            webInfo: this.webInfo.concat(res.data.data.search),
            count: res.data.count,
            isLast: false
          });

          if (this.webInfo.length >= this.count) {
            this.setData({
              isLast: true
            });
          }

          uni.hideLoading();
        } else {
          uni.hideLoading();
          this.setData({
            isLast: true
          });
          uni.showToast({
            title: '没有更多数据了',
            icon: 'none'
          });
        }
      }).catch(err => uni.hideLoading());
    },

    //业务信息
    shwoDetail(options) {
      let index = util.getValue('index', options);
      util.request('network.php', {
        action: 'service',
        id: this.webInfo[index].id
      }, 'POST').then(e => {
        e.data[0].work ? uni.showModal({
          title: '业务范围',
          content: e.data[0].work,
          confirmText: '关闭',
          showCancel: false
        }) : uni.showToast({
          title: '暂无业务信息',
          icon: 'none'
        });
      });
    },

    toDetail(e) {
      let index = util.getValue('index', e);
      uni.navigateTo({
        url: `../detail/detail?detailId=${this.webInfo[index].id}`
      });
    },

    // 打开地图
    navigator(options) {
      let latitude = parseFloat(util.getValue('lat', options));
      let longitude = parseFloat(util.getValue('lng', options));
      const location = util.bMapTransQQMap(longitude, latitude);
      longitude = location.lng;
      latitude = location.lat;
      let name = util.getValue('name', options);
      let address = util.getValue('addr', options);
      uni.openLocation({
        latitude,
        longitude,
        name,
        address
      });
    }

  }
};
</script>
<style>
.body{
  font-size: 24rpx;
}
.body .header {
  font-size: 30rpx;
  padding-left: 40rpx;
  height: 90rpx;
  line-height: 90rpx;
}
.body .header .local-icon {
  width: 22rpx;
  height: 26rpx;
  margin-right: 14rpx;
}
.body .header .city {
  color: #252525;
}
.body .header .arrow-down {
  width: 21rpx;
  height: 12rpx;
  margin-left: 12rpx;
}
.body .city-select {
  font-size: 30rpx;
  position: absolute;
  width: 100%;
  background-color: #fff;
  z-index: 99;
}
.body .city-select .address {
  border-bottom: 2rpx solid #ccc;
  color: #555;
}
.body .city-select .address .chouse {
  color: #f60;
}
.body .city-select .address .province,
.body .city-select .address .city,
.body .city-select .address .qu {
  height: 50vh;
  flex: 1;
  text-align: center;
  overflow-y: scroll;
  overflow-x: hidden;
}
.body .city-select .address .province .name,
.body .city-select .address .city .name,
.body .city-select .address .qu .name {
  width: 100%;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f1f1f1;
}
.body .city-select .address .province {
  flex-basis: 28%;
  background-color: #f1f1f1;
}
.body .city-select .address .city {
  padding-left: 18rpx;
  flex-basis: 28%;
  background-color: #fafafa;
}
.body .city-select .address .qu {
  padding-left: 18rpx;
  flex-basis: 44%;
  text-align: left;
}
.body .city-select .address .qu .name {
  padding-left: 11rpx;
}
.body .black {
  height: 50vh;
  background-color: rgba(0,0,0,0.5);
}
.search {
  height: 80rpx;
  padding-left: 30rpx;
  margin: 0 40rpx;
  margin-bottom: 34rpx;
  line-height: 80rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
}
.search .search-icon {
  width: 32rpx;
  height: 32rpx;
}
.search .type {
  color: #7a7a7a;
}
.search .type .select-icon {
  width: 16rpx;
  height: 12rpx;
  margin-left: 12rpx;
  vertical-align: middle;
}
.search .type picker {
  flex-shrink: 0;
}
.search .input {
  width: 467rpx;
  height: 42rpx;
  margin-left: 18rpx;
  margin-right: 23rpx;
  color: #bdbdbd;
  line-height: 42rpx;
  border-right: 2rpx solid #d4d4d4;
  font-size: 28rpx;
}
.lately-search {
  flex-wrap: wrap;
  margin: 0 40rpx;
  margin-bottom: 56rpx;
}
.lately-search .lately-title {
  height: 48rpx;
  margin-bottom: 18rpx;
  color: #7a7a7a;
  line-height: 48rpx;
}
.lately-search .lately-item {
  min-width: 118rpx;
  height: 48rpx;
  margin-right: 18rpx;
  margin-bottom: 18rpx;
  color: #bdbdbd;
  line-height: 48rpx;
  text-align: center;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}
.info-list {
  padding: 0 40rpx;
}
.info-list .info-item {
  padding-bottom: 42rpx;
  margin-bottom: 46rpx;
  border-bottom: 2rpx solid #f1f1f1;
}
.info-list .info-item .info-title {
  width: 85%;
  margin-bottom: 8rpx;
  color: #252525;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
  font-size: 32rpx;
}
.info-list .info-item .border .info {
  overflow: hidden;
  align-items: flex-start;

}
.info-list .info-item .border .info image {
  width: 20rpx;
  height: 22rpx;
  margin-right: 20rpx;
}
.info-list .info-item .border .info .base {
  width: 100%;
  margin-bottom: 22rpx;
}
.info-list .info-item .border .info .base .distance {
  padding-right: 20rpx;
  margin-right: 22rpx;
  border-right: 2rpx solid #cbcbcb;
  white-space: nowrap;
}
.info-list .info-item .border .info .base .time {
  margin-top: 8rpx;
  white-space: normal;
}
.info-list .info-item .control {
  flex-shrink: 0;
  flex-basis: 196rpx;
  justify-content: flex-end;
}
.info-list .info-item .control image {
  width: 78rpx;
  height: 78rpx;
}
.info-list .info-item .control image:first-child {
  margin-right: 18rpx;
}
.popup {
  margin: 0 44rpx;
  padding: 26rpx;
  color: #7a7a7a;
  border-radius: 12rpx;
  background-color: #fff;
}
.pop-title {
  margin-bottom: 16rpx;
  color: #141414;
  font-weight: bold;
}
.text-over{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
}

</style>